<template>
	<!-- 文章详情 -->
	<view class="newsdetaile">
		<image class="news_pic" v-if="news_info.image_url && !loaderr" @error="loaderrfun" :src="photo_cdn+news_info.image_url" mode="widthFix"></image>
		<view class="news_bodys">
			<view class="news_titlemax">{{news_info.title}}</view>
			<view class="news_d_author flex ali-c">
				<image v-if="news_info.photo" class="author_tximg" :src="photo_cdn+news_info.photo" mode=""></image>
				<view class="d_author_info">
					<view v-if="news_info.upload_name" class="d_author_name">{{news_info.upload_name}}</view>
					<view v-else-if="news_info.name" class="d_author_name">{{news_info.name}}</view>
					<view class="d_author_time">发布于 {{news_info.createtime}}</view>
				</view>
				
				<!-- ca_status：状态:0=取消收藏,1=已收藏 -->
				<view class="collect_btn_view">
					<view v-if="news_info.ca_status==0" class="collect_btn" @tap="collectfun">收藏</view>
					<view v-else class="collect_btn collect_btn_cancel" @tap="collectfun">取消收藏</view>
					<view  class="collect_btn" @tap="reportfun">举报</view>
					<view  class="collect_btn" @tap="shieldfun">屏蔽</view>
				</view>
			</view>
		</view>
		
		<view class="news_contents" style="font-size: 40rpx;">
			<!-- <rich-text :nodes="democountent"></rich-text> -->
			<jyf-parser :html="news_info.content" :domain="false" ref="article" selectable show-with-animation use-anchor
				@error="error" @imgtap="imgtap" @linkpress="linkpress" @parse="parse" @ready="ready">加载中...
			</jyf-parser>
		</view>
		
		<!-- 评论区 -->
		<view class="zu_comments">
			<hbcomment ref="hbComment" @add="add" @del="del" @like="like" @focusOn="focusOn" @revert='revert' @unfold="unfold" @cut_out="cut_out" :deleteTip="'确认删除？'"
			    :cmData="commentData" :user_id="user_id" @commentInput="commentInput"></hbcomment>
		</view>
		
		<login :hidden="isshowlogin" @close="closefun" @loginsucc="loginsucc"></login>
	</view>
</template>

<script>
	import hbcomment from '@/components/hbcomment/hbcomment.vue';
	import parser from '@/components/jyf-parser/jyf-parser'; // HBuilderX 2.5.5 及以上可以不需要
	import {detail,collectArticle,cancelCollectArticle,getCommentList,submitComment,delComment,likeComment,replyComment} from "@/utils/api/zuzhi.js";
	import {getUserinfo} from "@/utils/api/api.js";
	import config from "@/utils/config.js";
	let {uploadFile,photo_cdn} = config.baseUrl;
	
	import {lk_reverse} from "@/utils/libs/luokuangmap.js";
	export default {
		components:{
			'jyf-parser': parser,
			hbcomment,
		},
		data() {
			return {
				photo_cdn,
				article_id:"",//文章id
				news_info:{},
				loaderr:false,//缩略图是否加载失败
				page:0,
				isshowall:false,
				latitude:"",
				longitude:"",
				isshowlogin: false,
				province_id:'',
				user_id: 0,
				userinfo:{},
				commentData: {
					comment:[],
					commentSize:0,
					readNumer:0										
				},
				reqFlag: false // 请求标志，防止重复操作，true表示请求中
				
			}
		},
		onLoad(options) {
			this.article_id = options.article_id?options.article_id:"";
			this.newsdetailefun();	
			if(this.commentData.comment.length==0){
				this.page = 0;
				this.isshowall = false;
				this.commentData.comment =  [];
				this.getCommentListfun();
			}
			// #ifdef MP-WEIXIN
				wx.showShareMenu({
					withShareTicket:true,
					//设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
					menus:["shareAppMessage","shareTimeline"]
				})
			// #endif
		},
		onShow(){
			let token = uni.getStorageSync("token")
			if (!token) {
				// #ifdef MP-WEIXIN
				setTimeout(() => {
					this.isshowlogin = true;
				}, 1500)
				// #endif
			} else {
				this.getUserinfofun();
			}
			
			//取缓存的省份id
			let province_id = uni.getStorageSync("province_id");
			if(province_id){
				this.province_id = province_id;
			}
		},
		// #ifdef MP-WEIXIN
		//发送给朋友
		onShareAppMessage(res) {
			return {
				title: this.news_info.title,
				type: 0,
				path: '/pages/zupu/newsdetaile/newsdetaile?article_id=' + this.article_id,
				summary: "",
				imageUrl: photo_cdn+this.news_info.image_url
			}

		},
		//分享到朋友圈
		onShareTimeline(res) {
			return {
				title: this.news_info.title,
				type: 0,
				query: 'article_id=' + this.article_id,
				summary: "",
				imageUrl: photo_cdn+this.news_info.image_url
			}			 
		},
		// #endif
		onReachBottom() {
			if(!this.isshowall){
				this.getCommentListfun();
			}else{
				// this.$api.msg('没有更多了~');
			}
		},
		methods: {
			loginAuct(){
				let token = uni.getStorageSync("token")
				if (!token) {
					this.isshowlogin = true;//显示去登录
					return false;
				}
				return true;
			},
			//举报
			reportfun(){
				if(this.loginAuct()){
					uni.navigateTo({
						url:`/pagesim/center/report?title=反馈&contents=我要举报族志id为 ${this.article_id}  标题为 "${this.news_info.title}" 存在内容争议`
					})
				}
			},
			//屏蔽
			shieldfun(){
				if(this.loginAuct()){
					let shield_id = uni.getStorageSync("shield_id")
					shield_id = shield_id?shield_id:[];
					shield_id.push(this.article_id);
					shield_id = Array.from(new Set(shield_id));
					uni.setStorageSync("shield_id",shield_id);
					this.$api.msg("屏蔽成功!");
					setTimeout(()=>{
						uni.navigateBack({})
					},1000)
				}
			},
			//评论输入框弹起 获取定位
			commentInput(){
				let token = uni.getStorageSync("token");
				if(token && !this.province_id){
					console.info("获取定位");
					this.getlatandlng_one();
				}else{
					console.info("获取定位1");
				}
			},
			async getUserinfofun() {
				 await getUserinfo({}).then(res=>{
					 console.log(res)
					if(res.code != 401 ){
						this.userinfo = res.data.userinfo;
						this.user_id = res.data.userinfo.id;
					}
				})
			},
			// 登录校验
			async checkLogin() {
				let token = uni.getStorageSync("token");
				if(token){
					return true;
				}
				if (!token) {
					this.isshowlogin = true;
					return false;
				}
			},
			//关闭授权登录弹窗
			closefun() {
				this.isshowlogin = false;
			},
			//登录完成
			loginsucc() {
			
			},
			//缩略图加载失败
			loaderrfun(err){
				this.loaderr = true;
			},
			//解析完成时触发
			parse(res) {
			},
			//渲染完成时触发	
			ready(res) {
			},
			//图片被点击时触发	
			imgtap(res) {
				console.info(res,"图片点击");
			},
			//链接被点击时触发	
			linkpress(res) {
				// #ifdef APP-PLUS
				if (res.href && res.href.includes('http')) {
					res.ignore();
				}
				// #endif
			},
			//出错时触发	
			error(res) {
			
			},
			//获取文章详情
			async newsdetailefun(){
				let res = await detail({
					article_id:this.article_id,
				})
				if(res.code==1){
					this.news_info = res.data.info;
				}
			},
			//收藏和取消收藏接口
			async collectfun(){
				if(this.loginAuct()){
					// collectArticle,cancelCollectArticle
					let res = {};
					// ca_status：状态:0=取消收藏,1=已收藏
					if(this.news_info.ca_status==1){
						res = await cancelCollectArticle({
							article_id:this.article_id,
						})
					}else{
						res = await collectArticle({
							article_id:this.article_id,
						});
					}
					this.$api.msg(res.msg);
					//重新加载详情~
					this.newsdetailefun();
				}
			},
			// 输入框聚焦
			focusOn() {
				this.checkLogin();
			},
			//获取评论
			async getCommentListfun(){
				this.page++
				let res =  await getCommentList({
					page:this.page,
					article_id:this.article_id
				})
				if(res.code==1){
					let beforedata =  this.commentData.comment.filter(item => item.is_mock!=1 );//旧的
					let newcomlist = res.data.list?res.data.list:[];//新的
					newcomlist = newcomlist.map((item,index)=>{
						item.is_spread = 2;//折叠状态 默认收起
						return item;
					})
					this.commentData = {
						readNumer: res.data.total_count,
						commentSize: this.commentData.commentSize+newcomlist.length,//?
						comment: [...beforedata,...newcomlist]
					};
					if(res.data==null){
						this.isshowall = true;
						if(this.page>1){
							// this.$api.msg('没有更多了~');
						}
					}else if(newcomlist.length==0){
						this.isshowall = true;
						if(this.page>1){
							// this.$api.msg('没有更多了~');
						}
					}
				}else{
					if(res.data==null){
						this.isshowall = true;
						if(this.page>1){
							// this.$api.msg('没有更多了~');
						}
					}
				}
			},
			//新增评论
			async add(req){
				let boos = await this.checkLogin()
				if (!boos) {
					return
				}
				if (this.reqFlag) {
					uni.showToast({
						title: '操作频繁',
						duration: 1000
					});
					return
				}
				this.reqFlag = true;
				try{
					let res = await submitComment({
						article_id:this.article_id,
						content:req.content,
						province_id:this.province_id
					})
					if(res.code==1){
						this.$api.msg(res.msg)
						this.reqFlag = false;
						this.$refs.hbComment.addComplete();
						
						//模拟数据添加
						let mockdata = {
							is_mock:1,
							"id":res.data.info.id,
							"article_id":this.article_id,
							"user_id":this.user_id,
							"createtime":res.data.info.createtime,
							"likes":0,
							"content":res.data.info.content,
							"reply_id":0,
							"replytime":null,
							"reply_user_id":0,
							"ip":"",
							"status":0,
							"province":"",
							"nickname":this.userinfo.nickname,
							"avatar":this.userinfo.avatar,
							"sub":[
			
							]
						}
						
						this.commentData = {
							readNumer: this.commentData.readNumer+1,
							commentSize: this.commentData.commentSize+1,
							comment: [...this.commentData.comment,mockdata]
						};
					}else{
						this.$api.msg('没有获取到定位！')
					}
					this.reqFlag = false;
				}catch(err){
					console.log(err)
					this.reqFlag = false;
					
				}
			},
			//回复评论
			async revert(pId,content){
				let res = await replyComment({
					article_id:this.article_id,
					reply_id:pId,
					content:content,
					province_id:this.province_id
				})
				if(res.code==1){
					this.$api.msg(res.msg)
					this.$refs.hbComment.closeInput();
					
					let mockdata = {
						is_mock:1,
						"id":res.data.info.id,
						"article_id":this.article_id,
						"user_id":0,
						"createtime":res.data.info.createtime,
						"likes":0,
						"content":res.data.info.content,
						"reply_id":pId,
						"replytime":res.data.info.createtime,
						"reply_user_id":this.user_id,
						"ip":"",
						"status":0,
						"province":"",
						"nickname":this.userinfo.nickname,
						"avatar":this.userinfo.avatar,
					}
					let commentData  = this.commentData.comment;
					for(var i=0;i<commentData.length;i++){
						if(commentData[i].id==pId){
							commentData[i].sub.push(mockdata);//插入回复评论的数据
						}
					}
					this.commentData = {
						readNumer: this.commentData.readNumer+1,
						commentSize: this.commentData.commentSize+1,
						comment: [...commentData]
					};
				}
			},
			// 展开评论
			async unfold(data){
				let beforedata =  this.commentData.comment;//旧的
				beforedata[data.index].is_spread = 1;
				this.commentData.comment = beforedata;
			},
			//收起
			async cut_out(data){
				let beforedata =  this.commentData.comment;//旧的
				beforedata[data.index].is_spread = 2;
				this.commentData.comment = beforedata;
			},
			// 删除评论
			async del(commentId) {
				let bool = await this.checkLogin()
				if (!bool) {
					return
				}
				if (this.reqFlag) {
					uni.showToast({
						title: '操作频繁',
						duration: 1000
					});
					return
				}
				this.reqFlag = true;
				let res = await delComment({
					comment_id:commentId
				})
				if(res.code==1){
					this.$api.msg(res.msg)
					this.reqFlag = false;
					this.$refs.hbComment.deleteComplete(commentId);
				}
			},
			// 点赞评论
			async like(commentId) {
				let bool = await this.checkLogin()
				if (!bool) {
					return
				}
				if (this.reqFlag) {
					uni.showToast({
						title: '操作频繁',
						duration: 1000
					});
					return
				}
				this.reqFlag = true;
				let res = await  likeComment({
					comment_id:commentId
				})
				if(res.code==1){
					this.reqFlag = false;
					this.$refs.hbComment.likeComplete(commentId);
				}
				
			},
			//获取定位
			getlatandlng_one(){
				let istongyilat = uni.getStorageSync("istongyilat");
				if(istongyilat==1){
					this.getlatandlng();
				}else if(istongyilat==2){
					console.info("被拒绝了 不再询问！！");
				}
				else{
					// delCancel: true,
					if(uni.getSystemInfoSync().platform=='ios'){
						this.$showModal({
						    title:'温馨提示',
						    concent:'系统将获取您的位置信息,用于展示你的评论位置',
						    confirmVal:'继续',
							delCancel:true,
						    // cancelVal:'拒绝',
						}).then(res=>{
							uni.setStorageSync("istongyilat",1)
						    this.getlatandlng();
						}).catch(()=>{
						   //拒绝了~~
						   //拒绝了
						   uni.setStorageSync("istongyilat",2);
						})
					}else{
						this.$showModal({
						    title:'温馨提示',
						    concent:'系统将获取您的位置信息,用于展示你的评论位置 是否继续？',
						    confirmVal:'继续',
						    cancelVal:'拒绝',
						}).then(res=>{
							uni.setStorageSync("istongyilat",1)
						    this.getlatandlng();
						}).catch(()=>{
						   //拒绝了~~
						   //拒绝了
						   uni.setStorageSync("istongyilat",2);
						})
					}
				}
			},
			getlatandlng(){
				console.log('进来了')
				// #ifndef MP-WEIXIN
				uni.getLocation({
					// type: 'gcj02', //返回可以用于uni.openLocation的经纬度
					success: res => {
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						this.lk_reverse_fun({lon:res.longitude,lat:res.latitude});
					},
					fail: err => {
						console.info("err",err);
					}
				})
				// #endif

				// #ifdef MP-WEIXIN
				uni.authorize({
					scope: 'scope.userLocation',
					success: res=>{
						console.log('获取成功')
						uni.getFuzzyLocation({
							type: 'gcj02', //返回可以用于uni.openLocation的经纬度
							success: res => {
								console.info("111res",res);
								this.latitude = res.latitude;
								this.longitude = res.longitude;
								this.lk_reverse_fun({lon:res.longitude,lat:res.latitude});
							},
							fail: err => {
								console.info("err111",err);
							}
						})
					},
					fail: err =>{
						console.log(err,'获取失败');
					}

				})
				
				// #endif
				
			},
			//逆解析
			lk_reverse_fun(res){
				lk_reverse({
					lon:res.lon,
					lat:res.lat,
				}).then((success)=>{
					console.info('success',success);
					let result = success.result[0];
					console.info("province_id",result.properties.province_id,typeof(result.properties.province_id));
					this.province_id = result.properties.province_id;
					uni.getStorageSync("province_id",this.province_id);
					
					uni.getStorageSync("county_id",result.properties.county_id);
					// this.district = result.properties.county;
					// let county_id = parseInt(result.properties.county_id);
					// this.city_id = county_id-(county_id%100);
				})
			},
			
		}
	}
</script>

<style lang="scss">
	@import "./newsdetaile.scss";
</style>
